#include <iostream>
#include <string>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>

void Usage(std::string proc)
{
    std::cout << "\n\rUsage: " << proc << "serverip serverport" << std::endl;
}
//./tcpclient serverip serverport
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }
    const std::string serverip = argv[1];
    const uint16_t serverport = std::stoi(argv[2]);
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    inet_pton(AF_INET, serverip.c_str(), &server.sin_addr);
    socklen_t len = sizeof(server);

    while (true)
    {
        // 创建socket
        int sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (sockfd < 0)
        {
            std::cerr << "socket err" << std::endl;
            exit(1);
        }

        int cnt = 30;
        bool isreconnect = false;
        do
        {
            // tcp客户端要不要bind？1 要不要显示的bind？0 系统进行bind，随机端口
            // 客户端发起connect的时候，进行自动随机bind
            int n = connect(sockfd, (struct sockaddr *)&server, len);
            if (n < 0)
            {
                isreconnect = true;
                std::cerr << "connect err,isreconnect... cnt:" << cnt << std::endl;
                cnt--;
                sleep(1);
            }
            else
            {
                break;
            }
        } while (cnt && isreconnect);

        if (cnt == 0)
        {
            std::cerr << "user offline..." << std::endl;
            break;
        }
        std::string massege;
        std::cout << "Please Enter@ ";
        std::getline(std::cin, massege);
        int n = write(sockfd, massege.c_str(), massege.size());
        if (n < 0)
        {
            std::cerr << "write err" << std::endl;
        }

        char buff[4096];
        n = read(sockfd, buff, sizeof(buff));
        if (n > 0)
        {
            buff[n] = 0;
            std::cout << buff << std::endl;
        }
        close(sockfd);
    }

    return 0;
}
